

# pages/data_analysis.py - 数据分析页面
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import seaborn as sns
import matplotlib.pyplot as plt
from st_pages import add_page_title

# 检查认证状态
if 'authentication_status' not in st.session_state or not st.session_state.authentication_status:
    st.error("请先登录!")
    st.stop()

add_page_title()

# 数据上传和分析
st.markdown("### 📁 数据上传")

uploaded_file = st.file_uploader(
    "选择CSV文件进行分析",
    type=['csv'],
    help="支持CSV格式文件"
)

if uploaded_file is not None:
    # 读取上传的文件
    try:
        df = pd.read_csv(uploaded_file)
        
        st.success(f"文件上传成功! 数据形状: {df.shape}")
        
        # 数据预览
        st.markdown("### 📋 数据预览")
        st.dataframe(df.head(), use_container_width=True)
        
        # 数据统计信息
        col1, col2 = st.columns(2)
        
        with col1:
            st.markdown("#### 📊 基本统计")
            st.dataframe(df.describe(), use_container_width=True)
        
        with col2:
            st.markdown("#### ℹ️ 数据信息")
            buffer = []
            buffer.append(f"行数: {df.shape[0]:,}")
            buffer.append(f"列数: {df.shape[1]:,}")
            buffer.append(f"缺失值: {df.isnull().sum().sum():,}")
            buffer.append(f"重复行: {df.duplicated().sum():,}")
            
            for info in buffer:
                st.text(info)
        
        # 数据可视化选项
        st.markdown("### 📈 数据可视化")
        
        numeric_columns = df.select_dtypes(include=[np.number]).columns.tolist()
        
        if len(numeric_columns) >= 2:
            viz_type = st.selectbox(
                "选择图表类型",
                ["散点图", "柱状图", "箱线图", "热力图"]
            )
            
            if viz_type == "散点图":
                col1, col2 = st.columns(2)
                with col1:
                    x_axis = st.selectbox("X轴", numeric_columns)
                with col2:
                    y_axis = st.selectbox("Y轴", numeric_columns)
                
                if st.button("生成散点图"):
                    fig = px.scatter(df, x=x_axis, y=y_axis, title=f"{x_axis} vs {y_axis}")
                    st.plotly_chart(fig, use_container_width=True)
            
            elif viz_type == "柱状图":
                column = st.selectbox("选择列", numeric_columns)
                if st.button("生成柱状图"):
                    fig = px.histogram(df, x=column, title=f"{column} 分布")
                    st.plotly_chart(fig, use_container_width=True)
            
            elif viz_type == "箱线图":
                column = st.selectbox("选择列", numeric_columns)
                if st.button("生成箱线图"):
                    fig = px.box(df, y=column, title=f"{column} 箱线图")
                    st.plotly_chart(fig, use_container_width=True)
            
            elif viz_type == "热力图":
                if st.button("生成相关性热力图"):
                    correlation_matrix = df[numeric_columns].corr()
                    fig, ax = plt.subplots(figsize=(10, 8))
                    sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', center=0, ax=ax)
                    st.pyplot(fig)
        
        else:
            st.warning("需要至少2个数值列才能进行可视化分析")
    
    except Exception as e:
        st.error(f"文件读取错误: {str(e)}")

else:
    # 演示数据分析
    st.markdown("### 🎯 演示数据分析")
    
    # 生成示例数据集
    @st.cache_data
    def generate_demo_data():
        np.random.seed(42)
        n_samples = 1000
        
        data = {
            'age': np.random.normal(35, 10, n_samples),
            'income': np.random.normal(50000, 15000, n_samples),
            'score': np.random.normal(75, 15, n_samples),
            'category': np.random.choice(['A', 'B', 'C'], n_samples),
            'satisfaction': np.random.uniform(1, 10, n_samples)
        }
        
        return pd.DataFrame(data)
    
    demo_df = generate_demo_data()
    
    st.info("这是一个包含1000行演示数据的分析示例")
    
    tab1, tab2, tab3 = st.tabs(["数据概览", "统计分析", "可视化"])
    
    with tab1:
        st.dataframe(demo_df.head(20), use_container_width=True)
        
    with tab2:
        col1, col2 = st.columns(2)
        with col1:
            st.write("**描述性统计**")
            st.dataframe(demo_df.describe())
        with col2:
            st.write("**分类统计**")
            st.write(demo_df['category'].value_counts())
    
    with tab3:
        fig1 = px.scatter(demo_df, x='age', y='income', color='category', 
                         title="年龄vs收入分布")
        st.plotly_chart(fig1, use_container_width=True)
        
        fig2 = px.histogram(demo_df, x='score', title="得分分布")
        st.plotly_chart(fig2, use_container_width=True)
